package org.fluidripple.socket.server;

import io.netty.bootstrap.AbstractBootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class NettyServer implements SmartInitializingSingleton {

    private int port = 6000;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private int bossThread = Runtime.getRuntime().availableProcessors();
    private int workerThread = bossThread * 2;
    private boolean isRunning = false;

    private AbstractBootstrap initialize() {
        bossGroup = new NioEventLoopGroup(bossThread,new DefaultThreadFactory("boss-thread", Thread.MAX_PRIORITY));
        workerGroup = new NioEventLoopGroup(workerThread,new DefaultThreadFactory("work-thread", Thread.MAX_PRIORITY));
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap
                .group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(NioChannelOption.SO_REUSEADDR, true)
                .option(NioChannelOption.SO_BACKLOG, 1024)
                .option(NioChannelOption.SO_KEEPALIVE,false)
                .childOption(NioChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializerImpl())
        ;
        return bootstrap;
    }

    @Override
    public void afterSingletonsInstantiated() {
        start();
    }

    public synchronized boolean start(){
        if (isRunning) {
            log.warn("=>netty服务在端口:{},已经运行", port);
            return isRunning;
        }
        AbstractBootstrap bootstrap = initialize();
        ChannelFuture future = bootstrap.bind(port).awaitUninterruptibly();
        future.channel().closeFuture().addListener(event -> {
            if (isRunning) {
                stop();
            }
        });
        if (isRunning = future.isSuccess()) {
            log.info("=>启动Netty程序，端口为：{}，boss线程：{}，worker线程：{}",port,bossThread,workerThread);
            return isRunning;
        }
        if (future.cause() != null) {
            log.error("=>服务启动失败", future.cause());
        }
        return isRunning;
    }

    public synchronized void stop() {
        if(bossGroup!=null){
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        log.warn("=>IOT服务停止运行!");
    }
}
